package com.zxq.factory.encoder.impl;

import com.zxq.factory.encoder.IFieldEncoder;
import com.zxq.memory.ByteArrayPools;

public class LongFieldEncoder implements IFieldEncoder<Long> {

    @Override
    public byte[] encoder(Long value, int len) {
        byte[] buff = ByteArrayPools.getBytes(len + "");
        if(value >= 0) {
            for (int i = 0; i < len; i++) {
                buff[len - 1 - i] = (byte) (value % 256);
                value = value / 256;
            }
        } else {
            //原码 -10 ,10的
            value = Math.abs(value);
            for (int i = 0; i < len; i++) {
                buff[len - 1 - i] = (byte) (value % 256);
                value = value / 256;
            }
            //反码
            for (int i = 0; i < len; i++) {
                buff[i] = (byte) ~ buff[i];
            }
            // 补码运算
            int prefix = 0;
            int index = len - 1;
            do{
                if(buff[index] == (byte)0xff) {
                    //0xff进位的时候置为零，下一位加一
                    //  log.info("index: " + index + " num:" + buff[index]);
                    buff[index] = 0;
                    prefix = 1;
                    index = index - 1;
                } else {
                    //补码 + 1
                    buff[index] = (byte) (buff[index] + prefix);
                    buff[index] += 1;
                    break;
                }
            }while (index > 0);
        }
        return buff;
    }
}
